<template>
  <el-card class="profile-container">
    <template #header>
      <div class="header">
        <span>个人信息</span>
        <el-button type="primary" @click="toggleEdit" v-if="!isEditing">编辑资料</el-button>
        <div v-else>
          <el-button type="success" @click="saveChanges" :loading="loading">保存</el-button>
          <el-button @click="cancelEdit">取消</el-button>
        </div>
      </div>
    </template>

    <div v-loading="loading">
      <el-form :model="userForm" :rules="rules" ref="formRef" label-width="100px" v-if="userInfo">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="userForm.userId" :disabled="!isEditing" />
        </el-form-item>
        
        <el-form-item label="邮箱">
          <el-input v-model="userForm.email" disabled />
        </el-form-item>
        
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="userForm.age" :min="1" :max="120" :disabled="!isEditing" />
        </el-form-item>
        
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userForm.gender" :disabled="!isEditing">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
            <el-radio :label="2">保密</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="角色">
          <el-tag v-for="role in roles" :key="role.roleId" type="success" style="margin-right: 5px">
            {{ role.roleName }}
          </el-tag>
        </el-form-item>
        
        <el-form-item label="酒店名称" v-if="hotelName">
          <span>{{ hotelName }}</span>
        </el-form-item>
        
        <el-form-item label="注册时间">
          <span>{{ userInfo.createTime }}</span>
        </el-form-item>
      </el-form>
      
      <el-empty description="暂无数据" v-else></el-empty>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getUserProfile, updateUserProfile } from '@/api/user'
import { useUserInfoStore } from '@/stores/userInfo'
import type { FormInstance, FormRules } from 'element-plus'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const formRef = ref<FormInstance>()
const loading = ref(false)
const isEditing = ref(false)
const userInfo = ref<any>(null)
const roles = ref<any[]>([])
const hotelName = ref<string>('')

// 表单数据
const userForm = reactive({
  userId: '',
  email: '',
  age: 0,
  gender: 1,
})

// 表单验证规则
const rules: FormRules = {
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' },
    { min: 3, max: 20, message: '用户ID长度应为3-20个字符', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'change' },
    { type: 'number', min: 1, max: 120, message: '年龄应为1-120之间的数字', trigger: 'change' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ]
}

// 加载个人信息
const loadUserProfile = () => {
  loading.value = true
  getUserProfile().then((res: any) => {
    const result = res.data
    console.log('获取个人信息响应:', result)
    
    if (result.code === 200 && result.data) {
      const profileData = result.data
      
      // 保存用户信息
      userInfo.value = profileData.user
      roles.value = profileData.roles || []
      hotelName.value = profileData.hotelName || ''
      
      // 填充表单数据
      userForm.userId = profileData.user.userId
      userForm.email = profileData.user.email
      userForm.age = profileData.user.age
      userForm.gender = profileData.user.gender
      
      console.log('加载的个人信息:', profileData)
    } else {
      ElMessage.error(result.msg || '获取个人信息失败')
    }
    loading.value = false
  }).catch((error) => {
    console.error('获取个人信息错误:', error)
    loading.value = false
    ElMessage.error('获取个人信息失败，请稍后重试')
  })
}

// 切换编辑模式
const toggleEdit = () => {
  isEditing.value = true
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
  
  // 重置表单数据
  if (userInfo.value) {
    userForm.userId = userInfo.value.userId
    userForm.age = userInfo.value.age
    userForm.gender = userInfo.value.gender
  }
  
  // 清除表单验证
  formRef.value?.clearValidate()
}

// 保存修改
const saveChanges = () => {
  formRef.value?.validate((valid: boolean) => {
    if (!valid) return
    
    // 确认是否修改用户ID
    const isUserIdChanged = userForm.userId !== userInfo.value.userId
    
    if (isUserIdChanged) {
      ElMessageBox.confirm('修改用户ID将会影响您的登录，确定要修改吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        submitChanges()
      }).catch(() => {
        // 取消修改用户ID，恢复原值
        userForm.userId = userInfo.value.userId
      })
    } else {
      submitChanges()
    }
  })
}

// 提交修改
const submitChanges = () => {
  loading.value = true
  
  const params: any = {
    newUserId: userForm.userId,
    age: userForm.age,
    gender: userForm.gender
  }
  
  // 仅当用户ID有修改时才发送
  if (userForm.userId === userInfo.value.userId) {
    delete params.newUserId
  }
  
  updateUserProfile(params).then((res: any) => {
    const result = res.data
    
    if (result.code === 200) {
      ElMessage.success('个人信息更新成功')
      
      // 如果修改了用户ID，需要更新全局状态
      if (params.newUserId) {
        // 更新Pinia中的用户信息
        const currentUserInfo = userInfoStore.userInfo
        if (currentUserInfo) {
          // 创建一个新的userInfo对象，确保保留所有原始属性
          const updatedUserInfo = {
            ...currentUserInfo,
            user: {
              ...currentUserInfo.user,
            userId: params.newUserId
            }
          }
          // 设置更新后的用户信息
          userInfoStore.setUserInfo(updatedUserInfo)
        }
      }
      
      // 重新加载个人信息
      loadUserProfile()
      
      // 退出编辑模式
      isEditing.value = false
    } else {
      ElMessage.error(result.msg || '更新个人信息失败')
    }
    loading.value = false
  }).catch((error) => {
    console.error('更新个人信息错误:', error)
    loading.value = false
    ElMessage.error('更新个人信息失败，请稍后重试')
  })
}

// 页面加载时获取个人信息
onMounted(() => {
  loadUserProfile()
})
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 20px auto;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 